#include "Channel.h"
#include "Connection.h"
Channel::Channel(EventLoop *loop, int fd)
    : fd_(fd), loop_(loop)
{
    // ep_ = loop_->ep();
}
// 返回关联的文件描述符
int Channel::fd() const
{
    return fd_;
}
// 返回是否已添加到 epoll 树
bool Channel::inpoll() const
{
    return inepoll_;
}
// 返回当前监视的事件集
uint32_t Channel::events() const
{
    return events_;
}
// 返回实际发生的事件集
uint32_t Channel::revents() const
{
    return revents_;
}

// 事件管理
// 设置使用边缘触发 (EPOLLET) 模式
void Channel::useet()
{
    events_ = events_ | EPOLLET;
}
// 启用读事件监视 (EPOLLIN)
void Channel::enablereading()
{
    events_ = events_ | EPOLLIN;
    // ep_->updatechannel(this);
    loop_->ep()->updatechannel(this);
}
// 标记已添加到 epoll 树
void Channel::setinepoll()
{
    inepoll_ = true;
}

void Channel::setrevents(uint32_t ev)
{
    revents_ = ev;
}

void Channel::handleevent()
{
    if (revents_ & EPOLLRDHUP)
    {
        // printf("client(eventfd=%d)disconnected\n", fd_);
        // close(fd_);
        printf("EPOLLRDHUP\n");
        closecallback_();
    }
    else if (revents_ & (EPOLLIN | EPOLLPRI))
    {   
        printf("EPOLLIN | EPOLLPRI\n");
        readcallback_();
    }
    else if (revents_ & EPOLLOUT) // 处理写事件
    {
        sendcallback_();
        printf("EPOLLOUT\n");
    }
    else
    { // 其他事件都视为错误
        // printf("else error\n");
        // close(fd_);
        errorcallback_();
    }
}

Channel::~Channel()
{
}

void Channel::setreadcallback(std::function<void()> f)
{
    readcallback_ = f;
}

void Channel::setclosecallback(std::function<void()> f)
{
    closecallback_ = f;
}
void Channel::seterrorcallback(std::function<void()> f)
{
    errorcallback_ = f;
}

void Channel::setsendcallback(std::function<void()> f)
{
    sendcallback_ = f;
}

void Channel::disablereading()
{
    events_&= ~EPOLLIN;
    loop_->ep()->updatechannel(this);
}
void Channel::enablewriting()
{
    events_|= EPOLLOUT;
    loop_->ep()->updatechannel(this);
}
void Channel::disablewriting()
{
    events_&= ~EPOLLOUT;
    loop_->ep()->updatechannel(this);
}